import React, {useEffect, useState} from 'react';
import Goal from "./Goal/Goal";
import {CircularProgress, Step, StepContent, StepLabel, Stepper, Tooltip, Typography} from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import Question from "./Question/Question";
import Visualize from "./Visualize/Visualize";
import {useDispatch, useSelector} from "react-redux";
import {setLeftDrawerMenuIndex, skipGQITutorial} from "../../../../redux/reducers/commonSettings";
import {getActiveGoals, resetSession, setActiveStep} from "../../../../redux/reducers/gqiEditor";
import {useHistory} from "react-router-dom";
import {GQITutorialSteps} from "../../../../assets/constants/data/data";
import TutorialSlides from "../Common/TutorialSlides/TutorialSlides";
import Indicator from "./Indicator/Indicator";
import {scrollToTop} from "../../../../assets/functions/functions";
import {makeStyles} from "@material-ui/styles";
import HelpOutlineIcon from '@material-ui/icons/HelpOutline';
import ScrollToTop from "../Common/ScrollTopWrapper/ScrollTopWrapper";
import ModalMessage from "../Common/Modal/ModalMessage";
import WbIncandescentIcon from '@material-ui/icons/WbIncandescent';

const useStyles = makeStyles(theme => ({
  gutterTop: {
    margin: theme.spacing(2, 0, 0, 0)
  },
  gutterBottom: {
    marginBottom: theme.spacing(2)
  },
  stepper: {
    backgroundColor: theme.palette.type === 'light' ? theme.palette.common.white : "#212121"
  },
  gutterRight: {
    marginRight: theme.spacing(1)
  }
}))


export default function GQIEditor(props) {
  // Props
  const {classes} = props

  // Constants from Redux store
  const openTutorial = useSelector((state) => state.commonSettings.gqiEditorTutorialSkip);
  const activeStep = useSelector((state) => state.gqiEditor.common.activeStep);
  const activeGoalsData = useSelector((state) => state.gqiEditor.fetchedData.activeGoals);

  // Local constants
  const dispatch = useDispatch();
  const history = useHistory();
  const styles = useStyles();
  const [openResetModal, setOpenResetModal] = useState(false);
  const [saveEditorModal, setSaveEditorModal] = useState(false);
  const [openBackToDashboardModal, setOpenBackToDashboardModal] = useState(false);
  const [dashboardModal, setDashboardModal] = useState(false);

  useEffect(() => {
    scrollToTop();
    if (activeGoalsData.length === 0) {
      dispatch(getActiveGoals());
    }
  }, [activeGoalsData])

  const handleStepJump = (value) => {
    dispatch(setActiveStep(value));
  }

  const handleStepForward = () => {
    dispatch(setActiveStep(activeStep + 1));
  }

  const handleStepBackward = () => {
    dispatch(setActiveStep(activeStep - 1));
  }

  const handleOpenTutorial = () => {
    dispatch(skipGQITutorial());
  }

  const handleResetSession = () => {
    dispatch(resetSession());
    setOpenResetModal(!openResetModal);
  }

  const handleBackToDashboard = () => {
    dispatch(setLeftDrawerMenuIndex(1));
    history.push('/dashboard');
  }

  const handleCompleteEdit = () => {
    setSaveEditorModal(!saveEditorModal);
  }

  const steps = [
    {
      name: "Goal",
      component: <Goal handleStepForward={handleStepForward}/>
    },
    {
      name: "Question",
      description: <Typography variant="body2"> Formulate a question for your analysis with at least four words.
        <b>Tip:-</b> It is a good practice to end your question with a <b>Question mark</b>.
      </Typography>,
      component: <Question handleStepForward={handleStepForward} handleStepBackward={handleStepBackward}/>
    },
    {
      name: "Indicators",
      description: <Typography variant="body2"> An indicator is the label or caption of a visualization. Select and
        directly reuse an
        existing indicator from the list of indicators. Customize an existing indicator and/or create a new custom
        indicator for your analysis.
      </Typography>,
      component: <Indicator classes={classes} handleStepForward={handleStepForward}
                            handleStepBackward={handleStepBackward}/>
    },
    {
      name: "Visualizations",
      description: <Typography variant='body2'> Visualization preview of the question and its associated indicator(s).
        Edit and/or save your question and get sharable codes. Codes will be available after the question is saved.
      </Typography>,
      component: <Visualize handleStepBackward={handleStepBackward} classes={classes}
                            dashboardModal={dashboardModal} setDashboardModal={setDashboardModal}
                            handleCompleteEdit={handleCompleteEdit}/>
    }];

  return (
    <>
      <Grid container direction="column">

        <Typography variant="h3" className={styles.gutterBottom}> GQI Editor </Typography>

        <Grid container justify="space-between" alignItems="center" lg={9}>

          <Grid item>
            <Typography>
              Choose a goal for your analysis, create a question and answer it using some visualizations
            </Typography>
          </Grid>

          <Grid item>
            <Tooltip arrow placement="bottom" title="Open tutorial">
              <WbIncandescentIcon onClick={handleOpenTutorial} color="primary" style={{cursor: "pointer"}}/>
            </Tooltip>
          </Grid>

        </Grid>

        {activeGoalsData.length !== 0 ? (
          <Stepper activeStep={activeStep} orientation="vertical" className={styles.stepper}>
            {steps.map((step, index) => {
              return (
                <Step key={index}>
                  <StepLabel>
                    <Grid container alignItems="center">
                      <Typography variant="h5" style={{marginRight: 8, cursor: "pointer"}}
                                  onClick={() => handleStepJump(index)}>
                        {step.name}
                      </Typography>
                      {activeStep === index && step.description ?
                        <Tooltip
                          arrow style={{cursor: "pointer"}} placement="right"
                          title={step.description}>
                          <HelpOutlineIcon color="action"/>
                        </Tooltip> : <></>}

                    </Grid>

                  </StepLabel>
                  <StepContent>
                    {step.component}
                  </StepContent>
                </Step>
              )
            })}
          </Stepper>
        ) : (
          <Grid container justify="center" alignItems="center" className={styles.gutterTop}>
            <CircularProgress size={50}/>
          </Grid>
        )}
      </Grid>

      <TutorialSlides state={openTutorial} handleOpen={handleOpenTutorial} tutorialSteps={GQITutorialSteps}/>

      <ScrollToTop/>

      {/* Modal: Alert the user to confirm restarting the editor process */}
      <ModalMessage
        dialogTitle={"You are about to reset your progress!"}
        dialogPrimaryContext={
          <Typography gutterBottom>
            This will remove all your progress in the editor, including your drafted Question and added indicators.
            Are you sure that you want to reset?
          </Typography>}
        openDialog={openResetModal}
        setOpenDialog={setOpenResetModal}
        primaryAction={handleResetSession}
        primaryButton={"reset"}
        tertiaryAction={() => setOpenResetModal(!openResetModal)}
        tertiaryButton={"cancel"}
      />
      <ModalMessage
        dialogTitle={"Your draft is saved."}
        dialogPrimaryContext={
          <Typography>
            You can come back again to edit your question from the <b>Dashboard</b>.
          </Typography>}
        openDialog={openBackToDashboardModal}
        setOpenDialog={setOpenBackToDashboardModal}
        primaryAction={handleBackToDashboard}
        primaryButton={"To dashboard"}
        tertiaryAction={() => setOpenBackToDashboardModal(!openBackToDashboardModal)}
        tertiaryButton={"Continue editing"}
      />
    </>
  )
}
